package com.orangelife.mobile.app.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.common.sp.CommSp2;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.ImageDownloader.ImageSize;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;

import org.apache.http.util.EncodingUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Deprecated
public class AdvertService extends Service {

	private final int ACTION_OK = 12;
	private final String TAG = AdvertService.class.getSimpleName();
	private ImageDownloader imageDownloader = ImageDownloader
			.getImageDownloader();

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 被销毁时启动自身，保持自身在后台存活
		startService(new Intent(AdvertService.this, AdvertService.class));
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		doJob();
		return super.onStartCommand(intent, flags, startId);
	}

	private Boolean flag = true;

	public void doJob() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (flag) {
					try {
						getAdvert();
						getIntearationAdvert();
					} catch (Exception e) {
						e.printStackTrace();
					}
					try {// 睡眠一段时间
						Thread.sleep(10000 * 6);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	private void getAdvert() throws Exception {

		Map<String, Object> rootMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("showLocation", "1");
		rootMap.put("map", map);
		rootMap.put("wat", ACTION_OK);
		rootMap.put("url", Constant.URL_ADVERT_LIST);

		new JSONRequest(
				JSONRequest.GET,
				rootMap,
				new com.orangelife.mobile.common.biz.JSONRequest.JSONRequestListener() {

					@Override
					public void request(int errCode, String buf) {
						if (errCode != 500) {
							downloadImg(buf, CommSp2.getCommID());
						}
					}

				}, HttpUtil.ACTION_URI);

	}

	private void getIntearationAdvert() throws Exception {

		Map<String, Object> rootMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("showLocation", "2");
		rootMap.put("map", map);
		rootMap.put("wat", ACTION_OK);
		rootMap.put("url", Constant.URL_MY_SCORE_ADVERT_LIST);

		new JSONRequest(
				JSONRequest.GET,
				rootMap,
				new com.orangelife.mobile.common.biz.JSONRequest.JSONRequestListener() {

					@Override
					public void request(int errCode, String buf) {
						if (errCode != 500) {
							downloadImg(buf, CommSp2.getCommID());
						}
					}

				}, HttpUtil.ACTION_URI);

	}

	/**
	 * 存储 广告信息
	 *
	 * @param str
	 * @param merid
	 * @return
	 */
	public void saveJsonToFile(String str, String merid) {

		FileOutputStream out = null;

		if (merid == null) {
			return;
		}
		String file_path = Constant.FOLDER_PATH + "."
				+ StringUtil.Md5(merid, 32) + ".dec";
		try {
			File file = new File(file_path);

			File filePath = new File(Constant.FOLDER_PATH);
			if (!filePath.exists()) {
				if (!filePath.mkdirs()) {
					if (filePath.getParentFile().exists()) {
						filePath.getParentFile().delete();
						filePath.mkdirs();
					}
				}
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			out = new FileOutputStream(file);
			byte[] bytes = str.getBytes();
			out.write(bytes);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {

				}

			}
		}

	}

	/**
	 * 读取广告信息
	 *
	 * @param merid
	 * @return
	 */
	public static String getFileToJson(String merid) {

		FileInputStream fin = null;
		String res = "";
		if (merid == null) {
			return res;
		}
		String file_path = Constant.FOLDER_PATH + "."
				+ StringUtil.Md5(merid, 32) + ".dec";
		try {
			File file = new File(file_path);
			if (file.exists()) {
				fin = new FileInputStream(file_path);

				int length = fin.available();
				if (length == 0) {
					return res;
				}
				byte[] buffer = new byte[length];
				fin.read(buffer);

				res = EncodingUtils.getString(buffer, "UTF-8");

				return res;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {

				}

			}
		}
		return res;
	}

	/**
	 * 下载广告图片
	 *
	 * @param str
	 */
	@SuppressWarnings("unchecked")
	private void downloadImg(String str, String fileName) {
		Map<String, Object> listmap = JSONHelper
				.jsonToMap(str);
		if (listmap.get("errCode").equals("0")) {
			saveJsonToFile(str, fileName);
			if (listmap.get("pageEntity") != null
					&& !"".equals(listmap.get("pageEntity").toString())
					&& !"null".equals(listmap.get("pageEntity").toString())) {
				List<Map<String, Object>> pageEntity = (List<Map<String, Object>>) listmap
						.get("pageEntity");
				for (Map<String, Object> map : pageEntity) {
					if (map.get("pics").toString().indexOf("http") > -1)
						if (imageDownloader != null)
							imageDownloader.saveBitmapToFile(map.get("pics")
									.toString(),
									ImageSize.IMAGE_SIZE_SMALL_JPG);
				}
			}
		}
	}
}
